package joSaysHello.server;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailHandler {
	private static MailHandler instance;

	private Session session;

	private MailHandler(Session session) {
		this.session = session;
	}

	public static MailHandler getInstance() {
		if (instance == null) {
			Properties props = new Properties();
			//props.setProperty("mail.smtp.host", "smtp.mail.yahoo.com");
			//props.setProperty("mail.smtp.auth", "true");
			Session session = Session.getDefaultInstance(props, null);
			instance = new MailHandler(session);
		}
		return instance;
	}

	public boolean sendMail(String subject, String text, String[] tos) {
		String from = "noreply@jo-says-hello.appspotmail.com";
		Message m = new MimeMessage(session);
		try {
			m.setSubject(subject);
			m.setText(text);
			m.setFrom(new InternetAddress(from, "jo-says-hello"));
			for (String to : tos)
				m.addRecipient(RecipientType.TO, new InternetAddress(to));
			Transport.send(m);
			return true;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return false;
		}
	}
}
